package com.cch.cooperation.api.common.exception;

import com.cch.cooperation.common.exception.BizException;
import com.cch.cooperation.common.web.response.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 统一异常处理
 *
 * @author cch
 */
@Slf4j
@RestControllerAdvice
public class ExceptionController {

    @ExceptionHandler(Throwable.class)
    public Response<Void> handler(Throwable e) {
        if (e instanceof BizException) {
            return Response.fail(e.getMessage());
        }
        if (e instanceof HttpRequestMethodNotSupportedException) {
            return Response.fail("不支持的请求方式，异常:" + e.getMessage());
        }
        if (e instanceof IllegalStateException || e instanceof HttpMessageNotReadableException
                || e instanceof BindException) {
            return Response.fail("请求的参数无法解析，异常:" + e.getMessage());
        }
        log.error("捕获到未处理的异常", e);
        return Response.fail("系统发生异常，请联系管理员处理");
    }
}
